package com.i2863.shiroDemo.fileupload;

import com.baidu.ueditor.define.AppInfo;
import com.baidu.ueditor.define.BaseState;
import com.i2863.shiroDemo.util.HttpSessionUtils;
import com.i2863.shiroDemo.util.StringUtils;
import com.i2863.shiroDemo.util.UploadException;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.commons.io.output.ByteArrayOutputStream;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件上传至Qinniu服务器
 *
 * @author cexy
 * @create 2017-06-28 10:20
 **/
public class Upload2Qiniu {

    public static BaseState upload(InputStream is, String path, long maxSize,Integer siteId) throws Exception {
        QiniuUpload qiniuUpload = getQiniuUpload(siteId);
        byte[] bytes = toByteArray(is);
        if (bytes.length > maxSize) {
            return new BaseState(false, AppInfo.MAX_SIZE);
        }
        String filePath = qiniuUpload.upload(path, bytes);
//        Map<String,Object> map = QiNiuUtil.getUploadManagerForSiteid(siteId);
//        UploadManager uploadManager = (UploadManager) map.get("uploadManager");
//        Response res = uploadManager.put(bytes, path, (String)map.get("token"));
//        String body = res.bodyString();
//        JSONObject object = JSON.parseObject(body);
//        String host = (String) map.get("host");
        BaseState state = new BaseState(true);
        state.putInfo("size", bytes.length);
        state.putInfo("url", filePath);
        state.putInfo("title", path);
        return state;
    }

    public static BaseState upload(byte[] data, String path,Integer siteId) throws Exception {
//        QiniuUpload qiniuUpload = new QiniuUpload();
        QiniuUpload qiniuUpload = getQiniuUpload(siteId);
        String filePath = qiniuUpload.upload(path, data);
//        Map<String,Object> map = QiNiuUtil.getUploadManagerForSiteid(siteId);
//        UploadManager uploadManager = (UploadManager) map.get("uploadManager");
//        Response res = uploadManager.put(data, path, (String)map.get("token"));
//        String body = res.bodyString();
//        JSONObject object = JSON.parseObject(body);
//        String host = (String) map.get("host");
        BaseState state = new BaseState(true);
        state.putInfo("size", data.length);
        state.putInfo("url", filePath);
        state.putInfo("title", path);
        return state;
    }

    private static QiniuUpload getQiniuUpload(Integer siteId) {
        final String url = "http://vms.i2863.com/api";
        Map<String, String> params = new HashMap<>();
        params.put("method", "orgInfo");
        params.put("siteId", siteId.toString());

        // 获取用户信息
        String info = null;
        try {
            info = HttpSessionUtils.httpPost(HttpSessionUtils.buildHttpClient(),url,params);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(StringUtils.isBlank(info)){
            throw new UploadException("该站点下上传文件的参数获取失败");
        }
        JsonObject userObject = JsonParser.parseString(info).getAsJsonObject();
        if (("null").equals(userObject.get("data").toString()) || "".equals((userObject.get("data").toString()))) {
            throw new UploadException("该站点下上传文件的参数获取失败");
        }
        String ak = ((JsonObject) userObject.get("data")).get("ak").getAsString();
        String sk = ((JsonObject) userObject.get("data")).get("sk").getAsString();
        String host = ((JsonObject) userObject.get("data")).get("host").getAsString();
        String bucket = ((JsonObject) userObject.get("data")).get("bucket").getAsString();

        return new QiniuUpload(ak, sk, bucket, host);
    }

    private static byte[] toByteArray(InputStream inStream) throws IOException {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[5120];
        int len;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        outStream.close();
        inStream.close();
        return outStream.toByteArray();
    }


}
